<template>
    <div id="pdf_container">
        <div id="pdfDiv"></div>
    </div>
</template>

<script>
import PDFJS from './pdfjs-dist';
import './pdfjs-dist/web/pdf_viewer.css';
import * as pdfjsViewer from './pdfjs-dist/web/pdf_viewer';

export default {
    data() {
        return {
            pdfDoc: null,
            pdfPage: null,
            loading: false,
            contextWidth: 0,
            CSS_UNITS: 96.0 / 72.0
        };
    },
    props: ['src', 'page', 'scale', 'rotate', 'onLoad', 'onError'],
    computed: {
        total: function () {
            if (this.pdfDoc) {
                return 0;
            }
            return this.pdfDoc.numPages;
        }
    },
    watch: {
        src: function (val) {
            if (val) {
                this.showPDF();
            }
        },
        page: function () {
            console.log('sa');
            this.renderPage();
        },
        scale: function () {
            this.renderPage();
        },
        rotate: function () {
            this.renderPage();
        }
    },
    mounted() {
        PDFJS.GlobalWorkerOptions.workerSrc = './pdfjs-dist/build/pdf.worker.js';
        if (this.src) {
            this.loading = true;
            this.showPDF();
        }
        var container = document.getElementById('pdfDiv');
        if (container) {
            this.contextWidth = container.clientWidth;
        }
    },
    methods: {
        showPDF: function () {
            const self = this;
            PDFJS.getDocument(self.src)
                .then(function (pdf) {
                    self.pdfDoc = pdf;
                    self.renderPage(1);
                    self.loading = false;

                    if (self.onLoad) {
                        console.log(pdf);
                        self.onLoad(pdf);
                    }
                })
                ['catch']((err) => {
                    self.loading = false;
                    console.error('加载pdf出错：' + err);
                    if (self.onError) {
                        self.onError(err);
                    }
                });
        },
        renderPage: function (page = null) {
            console.log('as');
            const self = this;
            var container = document.getElementById('pdfDiv');

            this.pdfDoc.getPage(page || this.page).then(function (pdfPage) {
                container.innerHTML = '';

                self.pdfPage = pdfPage;

                var viewport = pdfPage.getViewport(self.scale, self.rotate);

                const tmpscale = self.contextWidth / (viewport.width * self.CSS_UNITS);

                var pdfPageView = new pdfjsViewer.PDFPageView({
                    container: container,
                    id: self.page,
                    scale: tmpscale,
                    rotate: self.rotate,
                    defaultViewport: viewport,
                    textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory(),
                    annotationLayerFactory: new pdfjsViewer.DefaultAnnotationLayerFactory()
                });

                pdfPageView.setPdfPage(pdfPage);
                pdfPageView.draw();
            });
        },
        print: function (dpi, pageNumberOnly) {
            console.log(dpi, pageNumberOnly);
            const page = document.querySelector('#pdfDiv');
            this.Print(page);
            const self = this;
            if (this.pdfPage === null) return;

            // 1in == 72pt
            // 1in == 96px
            var PRINT_RESOLUTION = dpi === undefined ? 150 : dpi;
            var PRINT_UNITS = PRINT_RESOLUTION / 72.0;
            var CSS_UNITS = 96.0 / 72.0;

            var iframeElt = document.createElement('iframe');

            new Promise(function (resolve, reject) {
                iframeElt.frameBorder = '0';
                iframeElt.scrolling = 'no';
                iframeElt.width = '0px;';
                iframeElt.height = '0px;';
                iframeElt.style.cssText = 'position: absolute; top: 0; left: 0';

                iframeElt.onload = function () {
                    resolve(this.contentWindow);
                };

                window.document.body.appendChild(iframeElt);
            })
                .then(function (win) {
                    win.document.title = '';
                    return self.pdfDoc.getPage(1).then(function (page) {
                        var viewport = page.getViewport(1);
                        win.document.head.appendChild(win.document.createElement('style')).textContent = '@supports ((size:A4) and (size:1pt 1pt)) {' + '@page { margin: 1pt; size: ' + (viewport.width * PRINT_UNITS) / CSS_UNITS + 'pt ' + (viewport.height * PRINT_UNITS) / CSS_UNITS + 'pt; }' + '}' + '@media print {' + 'body { margin: 0 }' + 'canvas { page-break-before: avoid; page-break-after: always; page-break-inside: avoid }' + '}' + '@media screen {' + 'body { margin: 0 }' + '}' + '';
                        return win;
                    });
                })
                .then(function (win) {
                    var allPages = [];
                    for (var pageNumber = 1; pageNumber <= self.pdfDoc.numPages; ++pageNumber) {
                        if (pageNumberOnly !== undefined && pageNumberOnly.indexOf(pageNumber) === -1) continue;

                        allPages.push(
                            self.pdfDoc.getPage(pageNumber).then(function (page) {
                                var viewport = page.getViewport(1);

                                var printCanvasElt = win.document.body.appendChild(win.document.createElement('canvas'));
                                printCanvasElt.width = viewport.width * PRINT_UNITS;
                                printCanvasElt.height = viewport.height * PRINT_UNITS;

                                return page.render({
                                    canvasContext: printCanvasElt.getContext('2d'),
                                    transform: [
                                        // Additional transform, applied just before viewport transform.
                                        PRINT_UNITS,
                                        0,
                                        0,
                                        PRINT_UNITS,
                                        0,
                                        0
                                    ],
                                    viewport: viewport,
                                    intent: 'print'
                                }).promise;
                            })
                        );
                    }

                    Promise.all(allPages)
                        .then(function () {
                            win.focus(); // Required for IE
                            win.print();
                            iframeElt.parentNode.removeChild(iframeElt);
                        })
                        .catch(function (err) {
                            iframeElt.parentNode.removeChild(iframeElt);
                            throw err;
                        });
                });
        }
    }
};
</script>

<style>
#pdf_container {
    width: 100%;
    height: 100%;
}
#pdf_container #pdfDiv {
    width: 100%;
    height: 100%;
}
</style>
